var prefix = "/member/manage";
$(function () {
    load();
});
$('#membersTable').on('load-success.bs.table', function (e, data) {
    if (data.total && !data.rows.length) {
        $('#membersTable').bootstrapTable('selectPage').bootstrapTable('refresh');
    }
});

function load() {
    $('#membersTable').bootstrapTable(
            {
                method: 'get', // 服务器数据的请求方式 get or post
                url: prefix + "/list", // 服务器数据的加载地址
                showRefresh: true,
                // showToggle : true,
                iconSize: 'outline',
                // toolbar: '#exampleToolbar',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                pageList:[10,20,50],
                // queryParamsType : "limit",
                // //设置为limit则会发送符合RESTFull格式的参数
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                // search : true, // 是否显示搜索框
                showColumns: true, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者
                // "server"
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: params.offset,
                        order: 'desc',
                        follow: $.trim($("#follow").val()),
                        startDate: $.trim($("#startDate").val()),
                        endDate: $.trim($("#endDate").val()),
                        keyword:$("#keyword").val(),
                        centreId: $('#centreId').val(),
                        liansuoId: $('#teamId').val(),
                        isUserAgent: $('#isUserAgent').val(),
                      //  isClerk: 0,
                    };
                },
                // //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
                // queryParamsType = 'limit' ,返回参数必须包含
                // limit, offset, search, sort, order 否则, 需要包含:
                // pageSize, pageNumber, searchText, sortName,
                // sortOrder.
                // 返回false将会终止请求
                columns: [
                    {
                        field:'id',
                        title: '编号'
                    },
                    {
                        field:'avatar',
                        title: '头像',
                        formatter: function (value, row, index) {
                            return '<div id="main" style="width:120%;"><div style="width:10%" class="col-sm-2"><img style="width:50px;height:50px;" src=' + value + '></div>';
                        }
                    },
                    {
                        field:'nickname',
                        title: '用户名',
                        formatter: function (value, row, index) {
                            var name = '';
                            if(value != '' && value != null){
                                name = value;
                            }else{
                                if(row.realname != '' && row.realname != null){
                                    name = row.realname;
                                }
                            }
                            return name;
                        }
                    },
                    {
                        field:'gender',
                        title: '性别',
                        formatter: function (value, row, index) {
                            if (value == 1) {
                                return '<span class="label label-success">男</span>';
                            }else if(value == 2){
                                return '<span class="label label-danger">女</span>';
                            }else{
                                return '<span class="label label-default">保密</span>';
                            }
                        }
                    },
                    {
                        field:'mobile',
                        title: '手机号码'
                    },
                    {
                        field:'createtime',
                        title: '注册时间'
                    },
                    // {
                    //     field: 'avatar',
                    //     title: '会员信息',
                    //     formatter: function (value, row, index) {
                    //     	var name = '';
                    //     	if(row.nickname != '' && row.nickname != null){
                    //     		name = row.nickname;
                    //     	}else{
                    //     		if(row.realname != '' && row.realname != null){
                    //     			name = row.realname;
                    //     		}
                    //     	}
                    //         return '<div id="main" style="width:120%;"><div style="width:10%" class="col-sm-2"><img style="width:50px;height:50px;" src=' + value + '></div>'
                    //             + '<div style="width:90%" class="col-sm-2">[ID:'+row.id+']-'+name+'<br>'+'注册时间:'+row.createtime+ '<br>'+ '手机号码:'+ row.mobile +'</div></div>';
                    //     }
                    // },
                    {
                        field: 'credit2',
                        title: '消费统计',
                        formatter: function (value, row, index) {
                        	var orderSum = '';
                        	var paypriceSum = '';
                        	if (row.allorder) {
                        		orderSum = '消费次数:'+row.allorder+'<br>';
                            }
                            return orderSum + paypriceSum + '余额:'+row.credit2;
                        }
                    },
                    {
                        field:'integral',
                        title: '积分'
                    },
                    {
                        field: 'isteam',
                        title: '等级',
                        formatter: function (value, row, index) {
                        	var str = '';
                        	var isLock = '';
                        	var hmd = '';
                        	var ck = '';
                        	if (row.isteam == 0 && row.isVip == 0) {
                        		str = '&nbsp;<span class="label label-primary" style="background-color:#808080">普通用户</span>';
                            }
                        	if (row.isteam == 1) {
                        		str = '<span class="label label-primary">邀请成为门店中</span>';
                            }
                            if (row.isteam == 2) {
                        		str = '<span class="label label-primary">申请成为门店中</span>';
                            }
                            if (row.isteam == 3) {
                                str = '<span class="label label-primary">门店</span>';
                            }
                            if (row.isteam == 4) {
                        		str = '<span class="label label-primary">审核通过未开通</span>';
                            }
                            if (row.isLock == 0) {
                            	isLock = '&nbsp;<span class="label label-danger">未锁定</span>';
                            }
                            if (row.isLock == 1) {
                            	isLock = '&nbsp;<span class="label label-primary">已锁定</span>';
                            }
                            if (row.status == 9) {
                            	hmd = '&nbsp;<span class="label label-danger">黑名单</span><br>';
                            }else{
                            	hmd = '<br>';
                            }
                            if (row.isVip == 1) {
                                ck = '&nbsp;<span class="label label-danger" style="background-color:#FF00FF">创客</span><br>';
                            }else{
                                ck = '<br>';
                            }

                            return str + isLock + hmd + ck;
                        }
                    },
                    // {
                    //     field: 'province',
                    //     title: '地址',
                    //     formatter: function (value, row, index) {
                    //
                    //         return '<p>' + value + '-' + row.city + '-' + row.area + '</p><p>' + row.address + '</p>';
                    //     }
                    // },
                    {
                        field:'isUseragent',
                        title: '是否用户代理',
                        formatter: function (value, row, index) {
                            if (value == 1) {
                                return '<span class="label label-success">是</span>';
                            }else if(value == 0){
                                return '<span class="label label-danger">否</span>';
                            }
                        }
                    },
                    {
                        field:'isAccountManage',
                        title: '是否客户经理',
                        formatter: function (value, row, index) {
                            if (value == 1) {
                                return '<span class="label label-success">是</span>';
                            }else if(value == 0){
                                return '<span class="label label-danger">否</span>';
                            }
                        }
                    },

                    {
                    	field: 'id',
                        title: '操作',
                        align: 'center',
                        width:"30%",
                        formatter: function (value, row, index) {
                        	var yq = '';
                        	if(row.isteam == 1) {
                        		yq = '<a style="margin-left: 20px;" class="btn btn-success btn-sm ' + s_detail_h + '" href="#" mce_href="#" title="已发出邀请">' + '<i class="fa fa-user-plus"></i>已发出邀请</a> ';
                            }else{
                            	yq = '<a style="margin-left: 20px;" class="btn btn-success btn-sm ' + s_detail_h + '" href="#" mce_href="#" title="邀请成为门店" onclick="invitation(\''
                                + value + '\')">' + '<i class="fa fa-user-plus"></i>邀请成为门店</a> ';
                            }

                        	var sz = '<a class="btn btn-success btn-sm ' + s_detail_h + '" href="#" mce_href="#" title="设置为门店" onclick="setCommander(\''
                            + value + '\')">' + '<i class="fa fa-wrench"></i>设置为门店</a> ';
                        	
                        	 var xq = '<a class="btn btn-primary btn-sm ' + s_edit_h + '" href="#" mce_href="#" title="会员详情" onclick="edit(\''
                             + value + '\')"><i class="fa fa-edit"></i>会员详情</a> ';
                        	                              
                        	 var hmd = '';
                        	 var hmdString = '';
                        	 var hmdValue = '';
                        	 var agent ='';
                        	 var useragent = "";
                        	 var clerk = '';

                        	 if(row.isAgent == 1){
                        		 agent = '<a class="btn btn-primary btn-sm ' + s_agent_h + '" href="#" mce_href="#" title="取消代理" onclick="setAgent(\''
                                 + value + '\',0)"><i class="fa fa-user"></i>取消商户代理</a> ';
                        	 }else{
                        		 agent = '<a class="btn btn-primary btn-sm ' + s_agent_h + '" href="#" mce_href="#" title="成为代理" onclick="setAgent(\''
                                 + value + '\',1)"><i class="fa fa-user"></i>成为商户代理</a> ';
                        	 }

                        	 if(row.isUseragent == 1  && row.isAccountManage == 0){
                        		 useragent = '<a class="btn btn-primary btn-sm ' + s_useragent_h + '" href="#" mce_href="#" title="取消代理" onclick="cancelUseragent(\''
                                 + value + '\')"><i class="fa fa-user"></i>取消用户代理</a> ';
                        	 }else if(row.isUseragent == 0  && row.isAccountManage == 0){
                        		 useragent = '<a class="btn btn-primary btn-sm ' + s_useragent_h + '" href="#" mce_href="#" title="成为代理" onclick="setUseragent(\''
                                 + value + '\')"><i class="fa fa-user"></i>成为用户代理</a> ';
                        	 }


                        	 if(row.status == 9) {
                        		 hmd = '<a class="btn btn-warning btn-sm ' + s_hmd_h + '" href="#" title="移出黑名单"  mce_href="#" onclick="hmd(\''
	                             + value + '\', 1)"><i class="fa fa-remove"></i>移出黑名单</a> ';
                        		 
                        		 hmdString = '移出黑名单';
                        		 hmdValue = '1';
                        	 }else{
                        		 hmd = '<a class="btn btn-warning btn-sm ' + s_hmd_h + '" href="#" title="黑名单"  mce_href="#" onclick="hmd(\''
	                             + value + '\', 9)"><i class="fa fa-remove"></i>黑名单</a> ';
                        		 
                        		 hmdString = '加入黑名单';
                        		 hmdValue = '9';
                        	 }
                        	 if(row.isClerk == 0){
                        	     clerk = '<a class="btn btn-primary btn-sm ' + s_useragent_h + '" href="#" mce_href="#" title="成为店员" onclick="setClerk(\''
                                     + value + '\')"><i class="fa fa-user"></i>设置为店员</a> ';
                             }

                        	 var gDuo ='<div class="dropdown pull-right" style="text-align: left;position: absolute;z-index: auto;margin-top: -30px;">' +
                        			   '<button type="button" class="btn dropdown-toggle btn-primary btn-sm" id="dropdownMenu1" data-toggle="dropdown">=更多<span class="caret"></span></button>' +
                        		       '<ul class="dropdown-menu" style="left:0 !important;" role="menu" aria-labelledby="dropdownMenu1">' +
                        			      '<li role="presentation" class="' + s_hmd_h + '">' +
                        			           '<a role="menuitem" tabindex="-1" href="#" onclick="hmd(\''+value+'\', ' + hmdValue + ')">' + hmdString + '</a>' + 
                        			      '</li>' + 
                        			      '<li role="presentation" class="divider"></li>' + 
                        			      '<li role="presentation">' +
                        			           '<a role="menuitem" tabindex="-1" href="#" onclick="updateBondmoney(\''+value+'\')">修改保证金</a>' +
                                          '</li>' +
                                          '<li role="presentation" class="divider"></li>' +
                                          '<li role="presentation">' +
                                          '<a role="menuitem" tabindex="-1" href="#" onclick="walletChange(\''+value+'\')">修改资产</a>' +
                        			      '</li>' + 
                        			      '<li role="presentation" class="divider"></li>' + 
                        			      '<li role="presentation">' +
                        				       '<a role="menuitem" tabindex="-1" href="#" onclick="bondFlow(\''+value+'\')">保证金流水</a>' +
                                          '</li>' +
                                          '<li role="presentation" class="divider"></li>' +
                                          '<li role="presentation">' +
                        				       '<a role="menuitem" tabindex="-1" href="#" onclick="orderList(\''+value+'\')">订单记录</a>' +
                        			      '</li>' +
                        			      '<li role="presentation" class="divider"></li>' + 
			                   			  '<li role="presentation">' +
		                   				       '<a role="menuitem" tabindex="-1" href="#" onclick="balanceFlow(\''+value+'\')">余额流水</a>' +
		                   			      '</li>' +
		                   			      '<li role="presentation" class="divider"></li>' + 
		                   			    /*  '<li role="presentation">' +
		                   				       '<a role="menuitem" tabindex="-1" href="#" onclick="withdrawals(\''+value+'\')">提现记录</a>' +
		                   			      '</li>' +*/
                        		       '</ul>' +
                        	           '</div>';
                            
	                         return  yq + sz + xq + agent + useragent+ clerk + gDuo;
                              
                        }
                    }]
            });
}
function reLoad() {
    $('#membersTable').bootstrapTable('refresh');
}
function hmd(id, status) {
	var str = '';
	if(status == 9){
		str = '确定添加黑名单吗？';
	}else{
		str = '确定移出黑名单吗？';
	}
    layer.confirm(str, {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/hmd",
            type: "post",
            data: {
                'id': id,
                'status': status
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}
function batchRemove() {
    var rows = $('#membersTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        layer.msg("请选择要删除的数据");
        return;
    }
    layer.confirm("确认要删除选中的'" + rows.length + "'条数据吗?", {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
        var ids = new Array();
        // 遍历所有选择的行数据，取每条数据对应的ID
        $.each(rows, function (i, row) {
            ids[i] = row['centreId'];
        });
        $.ajax({
            type: 'POST',
            data: {
                "ids": ids
            },
            url: prefix + '/batchRemove',
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function () {
    });
}

function setAgent(id,isAgent) {
   var prompt = "";
   if(isAgent==1){
	   prompt ="确定设置该用户为代理吗？";
   }else{
	   prompt ="确定取消该用户代理吗？";
   }
    layer.confirm(prompt, {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
    	//防止重复点击
    	layer.open({type:1,title:false,closeBtn:false});
        $.ajax({
            type: 'POST',
            data: {
                "id": id,
                "isAgent":isAgent
            },
            url: prefix + '/setAgent',
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    reLoad();
                  //关闭所有弹窗
                    layer.closeAll();
                } else {
                    layer.msg(r.msg);
                  //关闭所有弹窗
                    layer.closeAll();
                }
            }
        });
    }, function () {
    });
}

function setClerk(id) {
    layer.open({
        id:'member_edit',
        type : 2,
        title : '设置店员',
        maxmin : true,
        shadeClose : false,
        area : [ '60%', '80%' ],
        content : prefix + '/editClerk/' + id
    });
}


function edit(id) {
    layer.open({
        id:'member_edit',
        type : 2,
        title : '会员详情',
        maxmin : true,
        shadeClose : false,
        area : [ '60%', '80%' ],
        content : prefix + '/edit/' + id
    });
}

function setUseragent(id) {
    layer.open({
        id:'member_edit',
        type : 2,
        title : '成为代理',
        maxmin : true,
        shadeClose : false,
        area : [ '60%', '80%' ],
        content : prefix + '/editUseragent/' + id
    });
}

function cancelUseragent(id) {
        var prompt = "确定取消该用户代理吗？";
	    layer.confirm(prompt, {
	        btn: ['确定', '取消']
	        // 按钮
	    }, function () {
	    	//防止重复点击
	    	layer.open({type:1,title:false,closeBtn:false});
	        $.ajax({
	            type: 'POST',
	            data: {
	                "id": id
	            },
		            url: prefix + '/deleteUseragent',
	            success: function (r) {
	                if (r.code == 0) {
	                    layer.msg(r.msg);
	                    reLoad();
	                  //关闭所有弹窗
	                    layer.closeAll();
	                } else {
	                    layer.msg(r.msg);
	                  //关闭所有弹窗
	                    layer.closeAll();
	                }
	            }
	        });
	    }, function () {
	    });
}


function add() {
    // iframe层
    layer.open({
        id:'centre_add',
        type: 2,
        title: '添加商户',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area : [ '60%', '80%' ],
        content: prefix + '/add' // iframe的url
    });
}


function detail(centreId) {
    layer.open({
        id:'centre_detail',
        type : 2,
        title : '商户详情',
        maxmin : true,
        shadeClose : false,
        area : [ '60%', '80%' ],
        content : prefix + '/detail/' + centreId // iframe的url
    });
}

function invitation(id) {
	layer.open({
        id:'member_invitation',
        type : 2,
        title : '发出邀请',
        maxmin : true,
        shadeClose : false,
        area : [ '60%', '80%' ],
        content : prefix + '/invitation/' + id
    });
}
function setCommander(id) {
	 layer.open({
	        id:'commander_setCommander',
	        type : 2,
	        title : '设为门店',
	        maxmin : true,
	        shadeClose : false,
	        area : [ '60%', '80%' ],
	        content : prefix + '/setCommander/' + id
	    });
}

function orderList(id) {
	 layer.open({
	        id:'commander_orderList',
	        type : 2,
	        title : '订单列表',
	        maxmin : true,
	        shadeClose : false,
	        area : [ '90%', '80%' ],
	        content : prefix + '/getOrderList/' + id
	    });
}

function updateBondmoney(id) {
	 layer.open({
	        id:'commander_updateBondmoney',
	        type : 2,
	        title : '修改保证金',
	        maxmin : true,
	        shadeClose : false,
	        area : [ '40%', '55%' ],
	        content : prefix + '/updateBondmoney/' + id
	    });
}

function walletChange(id) {
    layer.open({
        id:'commander_walletChange',
        type : 2,
        title : '修改资产',
        maxmin : true,
        shadeClose : false,
        area : [ '60%', '80%' ],
        content : prefix + '/walletChange/' + id
    });
}

function bondFlow(id) {
	 layer.open({
	        id:'commander_bondFlow',
	        type : 2,
	        title : '保证金流水',
	        maxmin : true,
	        shadeClose : false,
	        area : [ '60%', '80%' ],
	        content : '/flow/bond/bondFlowToMid/' + id
	    });
}

function balanceFlow(id) {
	 layer.open({
	        id:'commander_balanceFlow',
	        type : 2,
	        title : '余额流水',
	        maxmin : true,
	        shadeClose : false,
	        area : [ '60%', '80%' ],
	        content : '/flow/balance/balanceFlowToMid/' + id
	    });
}

/**
 * 用户列表导出excel
 */
function exportMembers() {
	 var  order =  'desc';
     var follow = $.trim($("#follow").val());
     var  startDate =  $.trim($("#startDate").val());
     var endDate = $.trim($("#endDate").val());
     var keyword = $("#keyword").val();
     var centreId =  $('#centreId').val();
    window.location.href = prefix + "/exportMembers?follow="+follow+"&startDate="+startDate+"&endDate="+endDate+"&centreId="+centreId+"&order="+order+"&keyword="+keyword;
}

function withdrawals(id) {
	 layer.open({
	        id:'commander_withdrawals',
	        type : 2,
	        title : '提现记录',
	        maxmin : true,
	        shadeClose : false,
	        area : [ '60%', '90%' ],
	        content : '/finance/withdrawals/withdrawalsToMid/' + id
	    });
}



